package com.soriya.nestlive.screen.channel

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Facebook
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.outlined.Sms
import androidx.compose.material.icons.twotone.Android
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.soriya.nestlive.R
import com.soriya.nestlive.application.MyApplication
import com.soriya.nestlive.component.CustomDivider
import com.soriya.nestlive.component.CustomImage
import com.soriya.nestlive.component.CustomOutlinedButton
import com.soriya.nestlive.component.LargeAdditionalText
import com.soriya.nestlive.component.LiveTag
import com.soriya.nestlive.component.MediumAdditionalText
import com.soriya.nestlive.component.MediumText
import com.soriya.nestlive.component.MediumTitle
import com.soriya.nestlive.component.NavMenu
import com.soriya.nestlive.component.NavMenuItem
import com.soriya.nestlive.component.ScreenBoxContent
import com.soriya.nestlive.component.ScreenColumnContent
import com.soriya.nestlive.component.SmallAdditionalText
import com.soriya.nestlive.component.SmallText
import com.soriya.nestlive.component.SmallTitle
import com.soriya.nestlive.component.SmallerAdditionalText
import com.soriya.nestlive.component.SmallerText
import com.soriya.nestlive.component.VideoCard
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.db.AppDataBase
import com.soriya.nestlive.model.Channel
import com.soriya.nestlive.model.Live
import com.soriya.nestlive.util.ToastUtil
import com.soriya.nestlive.util.WindowUtil
import com.soriya.nestlive.viewmodel.ChannelModel
import com.soriya.nestlive.viewmodel.LiveModel
import com.soriya.nestlive.viewmodel.VideoModel
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date

@Composable
fun ChannelDetailScreen(
    channelId: Long? = null, // Id为null时是MyChannel,
    toGoLive: () -> Unit,
    toChannelForm: () -> Unit,
    toVideoDetail: (Long) -> Unit,
    toLiveDetail: (Long) -> Unit
) {
    val context = LocalContext.current

    val model: ChannelModel = hiltViewModel()
    val channel by model.channelDetail.collectAsState()

    LaunchedEffect(Unit) {
        if (channelId == null) model.getMyChannel(false)
        else model.getDetailById(channelId)
    }

    if (channel == Channel.EMPTY) {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(0.3f))
        ) {
            CircularProgressIndicator(
                modifier = Modifier.width(64.dp)
            )
        }
    } else {
        val channelInfoDao = AppDataBase.getInstance(context).channelInfoDao()
        val myChannel by channelInfoDao.selectOne().collectAsState(initial = null)

        val isSelf = channelId == null || channelId == myChannel?.channelId

        val hasChannel = channel != null

        if (hasChannel)
            ChannelDetail(
                channel = channel as Channel,
                isSelf = isSelf,
                toGoLive = toGoLive,
                toVideoDetail = toVideoDetail,
                toLiveDetail = toLiveDetail
            )
        else
            EmptyChannel(toChannelForm)
    }
}

@Composable
private fun EmptyChannel(toChannelForm: () -> Unit) = ScreenColumnContent(
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    Icon(imageVector = Icons.Outlined.Sms, contentDescription = "Empty", tint = Color.Gray.copy(alpha = 0.5F), modifier = Modifier.size(160.dp))
    Spacer(modifier = Modifier.height(40.dp))
    LargeAdditionalText(text = "Empty")
    Spacer(modifier = Modifier.height(40.dp))
    Button(
        onClick = toChannelForm,
        shape = RoundedCornerShape(50),
        modifier = Modifier.fillMaxWidth()
    ) {
        Text(text = "创建频道")
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ChannelDetail(
    channel: Channel,
    isSelf: Boolean,
    toGoLive: () -> Unit,
    toVideoDetail: (Long) -> Unit,
    toLiveDetail: (Long) -> Unit
) = ScreenBoxContent(
    modifier = Modifier
        .padding(top = UIValue.VERTICAL_PADDING)
        .background(Brush.verticalGradient(0F to Color.White, 0.4F to Color(0xFFFAFAFA)))
) {
    val widthDp =  WindowUtil.getScreenWidthToDp(LocalContext.current)

    Column {
        Box {
            CustomImage(
                url = channel.backgroundCover,
                contentDescription = "Cover",
                shape = RoundedCornerShape(UIValue.MEDIUM_RADIUS),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(widthDp.dp / 3)
            )

            if (isSelf) {
                IconButton(
                    onClick = { /*TODO*/ },
                    modifier = Modifier
                        .align(Alignment.BottomEnd)
                        .padding(bottom = 6.dp, end = 6.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Edit,
                        contentDescription = "Edit my channel background",
                        tint = Color.White
                    )
                }
            }
        }

        AboutInfo(channel, isSelf)

        val pagerState = rememberPagerState(initialPage = 0)

        val coroutineScope = rememberCoroutineScope()

        NavMenu {
            NavMenuItem(title = "首页", select = pagerState.currentPage == 0) {
                coroutineScope.launch {
                    pagerState.animateScrollToPage(0)
                }
            }
            NavMenuItem(title = "关于", select = pagerState.currentPage == 1) {
                coroutineScope.launch {
                    pagerState.animateScrollToPage(1)
                }
            }
//            NavMenuItem(title = "Schedule", select = pagerState.currentPage == 2) {
//                coroutineScope.launch {
//                    pagerState.animateScrollToPage(2)
//                }
//            }
            NavMenuItem(title = "视频", select = pagerState.currentPage == 2) {
                coroutineScope.launch {
                    pagerState.animateScrollToPage(2)
                }
            }
        }

        HorizontalPager(
            pageCount = 3,
            state = pagerState,
            pageSpacing = UIValue.HORIZONTAL_PADDING,
            modifier = Modifier.fillMaxSize()
        ) { page ->
            when (page) {
                0 -> Home(channel) {
                    toLiveDetail(channel.id!!)
                }
                1 -> About()
                2 -> Videos(channelId = channel.id!!) {
                    toVideoDetail(it)
                }
            }
        }
    }

    if (isSelf) {
        Button(
            onClick = toGoLive,
            shape = CircleShape,
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .padding(bottom = 20.dp)
                .size(60.dp)
        ) {
            Icon(imageVector = Icons.Default.Add, contentDescription = "Go Live")
//            SmallText(text = "Go Live")
        }
    }
}

@Composable
private fun AboutInfo(
    channel: Channel,
    isSelf: Boolean = false
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(vertical = UIValue.VERTICAL_PADDING)
        ) {
            val height = 80.dp
            CustomImage(
//                url = "https://gimg0.baidu.com/gimg/src=https%3A%2F%2Fgameplus-platform.cdn.bcebos.com%2Fgameplus-platform%2Fupload%2Ffile%2Fimg%2F48ce8034a7378ce56a6ad5fdbfd0daac%2F48ce8034a7378ce56a6ad5fdbfd0daac.png&app=2000&size=f180,180&n=0&g=0n&q=85&fmt=jpeg?sec=0&t=c3aca64da2fb743cc44361dacf371198",
                url = channel.avatar,
                contentDescription = "Avatar",
                shape = CircleShape,
                modifier = Modifier.size(height)
            )

            Spacer(modifier = Modifier.width(UIValue.HORIZONTAL_PADDING))

            Column(
                verticalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .weight(1F)
                    .height(height)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    MediumTitle(text = channel.channelName)
                    Spacer(modifier = Modifier.width(6.dp))
                    Icon(imageVector = Icons.Default.CheckCircle, contentDescription = "Auth", tint = MaterialTheme.colors.primary, modifier = Modifier.size(18.dp))
                }

//                SmallerAdditionalText(text = "Streaming Overwatch 2 with 8.5k Views")
                SmallerAdditionalText(text = "Offline")

                Row {
                    SmallerText(text = "246K")
                    Spacer(modifier = Modifier.width(6.dp))
                    SmallerAdditionalText(text = "Followers")
                }
            }

            if (isSelf) {
                Button(
                    onClick = { /*TODO*/ },
                    shape = RoundedCornerShape(50)
                ) {
                    Icon(imageVector = Icons.Default.Edit, contentDescription = "Edit Button", modifier = Modifier.size(14.dp))
                    Spacer(modifier = Modifier.width(3.dp))
                    SmallText(text = "编辑")
                }
            }
        }

        Box {
            SmallText(
//                text = "Streaming Overwatch 2 with 8.5k Views Streaming Overwatch 2 with 8.5k Views Streaming Overwatch 2 with 8.5k Views Streaming Overwatch 2 with 8.5k Views",
                text = channel.about,
                maxLines = 3,
                lineHeight = 20.sp
            )
        }

        Row(
            modifier = Modifier.padding(vertical = UIValue.VERTICAL_PADDING)
        ) {
            Icon(imageVector = Icons.TwoTone.Android, contentDescription = "Facebook", tint = MaterialTheme.colors.primary)
            Spacer(modifier = Modifier.width(20.dp))
            Icon(imageVector = Icons.Default.Facebook, contentDescription = "Facebook", tint = MaterialTheme.colors.primary)
        }

        val channelModel: ChannelModel = hiltViewModel()
        val coroutineScope = rememberCoroutineScope()

        val context = LocalContext.current

        if (!isSelf) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth()
            ) {
                if (channel.isFollow == 0)
                    Button(
                        onClick = {
                            coroutineScope.launch {
                                channelModel.follow(channel.id!!).collect {
                                    channelModel.getDetailById(channel.id)
                                    ToastUtil.show(context = context, text = "订阅成功")
                                }
                            }
                        },
                        shape = RoundedCornerShape(50),
                        modifier = Modifier.weight(1F)
                    ) {
                        MediumText(text = "订阅频道")
                    }
                else
                    CustomOutlinedButton(
                        text = "取消订阅",
                        onClick = {
                            coroutineScope.launch {
                                channelModel.follow(channel.id!!).collect {
                                    channelModel.getDetailById(channel.id)
                                    ToastUtil.show(context = context, text = "取消订阅")
                                }
                            }
                        },
                        modifier = Modifier.weight(1F)
                    )

                Spacer(modifier = Modifier.width(10.dp))

                Button(
                    onClick = { /*TODO*/ },
                    shape = RoundedCornerShape(50),
                    modifier = Modifier.weight(1F)
                ) {
                    Icon(imageVector = Icons.Default.Star, contentDescription = "Subscribe Icon")
                    Spacer(modifier = Modifier.width(UIValue.HORIZONTAL_PADDING))
                    MediumText(text = "Subscribe")
                }
            }
        }
    }
}

@Composable
private fun Home(
    channel: Channel,
    onClickLive: () -> Unit
) {

    val liveModel: LiveModel = hiltViewModel()

    val historyList by liveModel.historyList.collectAsState()
    val live by  liveModel.liveDetail.collectAsState()

    LaunchedEffect(Unit) {
        liveModel.getHistory(channel.id!!)
    }

    Column(
        modifier = Modifier
            .padding(vertical = UIValue.VERTICAL_PADDING)
            .verticalScroll(rememberScrollState())
//            .fillMaxSize()
    ) {

        val context = LocalContext.current

        if (channel.liveState == 1) Column(
            modifier = Modifier.clickable(onClick = onClickLive)
        ) {
            liveModel.getLiveByChannelId(channel.id!!)

            Box {
                val screenWidthToDp = WindowUtil.getScreenWidthToDp(context)

                CustomImage(
                    url = live?.cover ?: "https://img2.baidu.com/it/u=3994669564,1460731068&fm=253&fmt=auto&app=138&f=JPEG?w=835&h=500",
                    contentDescription = "Live Cover",
                    shape = RoundedCornerShape(UIValue.LARGE_RADIUS),
                    modifier = Modifier
                        .fillMaxWidth()
                        .height((screenWidthToDp * 9 / 16).dp)
                )

                LiveTag(
                    modifier = Modifier
                        .align(Alignment.TopStart)
                        .padding(start = 16.dp, top = 10.dp)
                )

                SmallerText(
                    text = "8.5K Viewers",
                    color = Color.White,
                    modifier = Modifier
                        .align(Alignment.BottomStart)
                        .padding(start = 16.dp, bottom = 10.dp)
                        .clip(RoundedCornerShape(UIValue.SMALLER_RADIUS))
                        .background(MaterialTheme.colors.surface.copy(alpha = 0.7F))
                        .padding(horizontal = 6.dp, vertical = 4.dp)
                )
            }

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(vertical = UIValue.VERTICAL_PADDING)
            ) {
                MediumTitle(text = live?.liveName ?: "Empty", maxLines = 1, modifier = Modifier.weight(1F))
                Spacer(modifier = Modifier.width(10.dp))
                Icon(imageVector = Icons.Default.ArrowForward, contentDescription = "To Live", tint = MaterialTheme.colors.primary)
            }
        }

        Card(
            backgroundColor = MaterialTheme.colors.background
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(
                        horizontal = UIValue.HORIZONTAL_PADDING,
                        vertical = UIValue.VERTICAL_PADDING
                    )
            ) {
                SmallTitle(text = "直播历史")

                Spacer(modifier = Modifier.height(16.dp))

                if (historyList.isNotEmpty()) {
                    historyList.forEach { live ->
                        HistoryItem(live)
                    }
                    CustomDivider(text = "仅展示最近20条数据")
                } else {
                    CustomDivider(text = "暂无直播历史")
                }


            }
        }

    }
}

@Composable
private fun About() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        MediumTitle(text = "Description")

        MediumText(
            text = "This is the fantasy world \"Tivat\" where seven elements intersect.\n" +
                "In the distant past, people were given the power of driving elements through their faith in gods, and were able to build homes in the wilderness.\n" +
                "Five hundred years ago, the downfall of the ancient country caused the heavens and earth to mutate\n" +
                "Nowadays, the disaster sweeping across the mainland has ceased, but peace has not yet arrived as scheduled.\n" +
                "As the protagonist of the story, you drifted from outside the world and landed on the earth. You will travel freely in this vast world, meet companions, search for the seven gods who control the elements of the world, until you reunite with your separated blood relatives",
            lineHeight = 22.sp
        )
    }
}

@Composable
private fun Videos(
    channelId: Long,
    toVideoDetail: (Long) -> Unit
) {

    val videoModel: VideoModel = hiltViewModel()

    val items = remember {
        videoModel.getVideoListByChannelId(channelId)
    }.collectAsLazyPagingItems()

    if (items.itemCount == 0) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Spacer(modifier = Modifier.height(20.dp))
            Image(painter = painterResource(id = R.mipmap.empty), contentDescription = "Empty")
            MediumAdditionalText(text = "暂无数据")
        }
    } else {
        LazyColumn(
            modifier = Modifier.fillMaxSize()
        ) {
            items(
                count = items.itemCount,
                key = items.itemKey { it.id }
            ) {
                val item = items[it]
                VideoCard(data = item!!) {
                    toVideoDetail(item.id)
                }
            }

            item {
                CustomDivider(text = "已经到底了")
            }
        }
    }


}

@SuppressLint("SimpleDateFormat")
@Composable
private fun HistoryItem(live: Live) {
    Row {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.height(64.dp)
        ) {
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier.size(20.dp)
            ) {
                Icon(imageVector = Icons.Default.Star, contentDescription = "Live History Item", modifier = Modifier.size(16.dp))
            }

            Spacer(
                modifier = Modifier
                    .fillMaxHeight()
                    .width(1.dp)
                    .drawWithContent {
                        drawLine(
                            start = Offset.Zero,
                            end = Offset(x = 0F, y = size.height),
                            color = Color.Black,
                            pathEffect = PathEffect.dashPathEffect(
                                intervals = floatArrayOf(
                                    10F,
                                    10F
                                )
                            )
                        )
                    }
            )
        }

        Spacer(modifier = Modifier.width(10.dp))

        val startTime = live.startTime
        val date = startTime.split(" ")[0]
        val time = startTime.split(" ")[1]
        var endTime = "-:-"

        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
        val timeFormat = SimpleDateFormat("hh:mm")
        val parse = simpleDateFormat.parse(startTime)
        if (parse != null) {
            val endDate = parse.time + live.duration * 60 * 1000
            endTime = timeFormat.format(Date(endDate.toLong()))
        }

        Column {
            MediumText(text = date, lineHeight = 20.sp)
            SmallAdditionalText(text = "${time.substring(0 .. time.lastIndexOf(":"))} - $endTime ${live.liveName}")
        }
    }
}